<template>
  <div class="secondhand-forum">
    <!-- 搜索框 -->
    <van-search
      v-model="searchKeyword"
      placeholder="搜索论坛主题"
      shape="round"
      background="#f5e8d0"
      @search="onSearch"
      @cancel="onCancelSearch"
    >
      <template #left-icon>
        <van-icon name="search" color="#8b4513" />
      </template>
    </van-search>

    <!-- 创建主题区域 -->
    <div class="create-topic-area" v-if="isCreatingTopic">
      <div class="topic-header">
        <h3>创建新主题</h3>
        <van-button 
          size="mini" 
          plain 
          type="default" 
          @click="cancelCreateTopic"
        >
          取消
        </van-button>
      </div>
      
      <div class="topic-form">
        <van-field
          v-model="newTopic.title"
          placeholder="请输入主题标题"
          required
          @blur="validateTitle"
        />
        
        <div class="form-error" v-if="titleError">{{ titleError }}</div>
        
        <van-field
          v-model="newTopic.content"
          placeholder="请输入主题内容"
          type="textarea"
          autosize
          required
          @blur="validateContent"
        />
        
        <div class="form-error" v-if="contentError">{{ contentError }}</div>
        
        <van-button 
          round 
          type="primary" 
          color="#8b4513" 
          block
          @click="submitTopic"
          :disabled="!isFormValid"
          style="margin-top: 20px;"
        >
          发布主题
        </van-button>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="forum-actions" v-if="!isCreatingTopic">
      <van-button 
        size="small" 
        type="primary" 
        color="#8b4513"
        icon="plus" 
        @click="startCreateTopic"
      >
        创建主题
      </van-button>
    </div>

    <!-- 主题列表 -->
    <div class="topic-list">
      <div v-if="filteredTopics.length === 0" class="empty-topic">
        <van-icon name="chat-o" size="60" color="#ccc" />
        <p v-if="searchKeyword">没有找到匹配的论坛主题</p>
        <p v-else>论坛还没有主题哦，快来创建吧！</p>
        <van-button 
          round 
          type="primary" 
          color="#8b4513" 
          @click="startCreateTopic"
          style="margin-top: 15px;"
        >
          创建主题
        </van-button>
      </div>

      <div 
        v-for="(topic, topicIndex) in filteredTopics" 
        :key="topic.id" 
        class="topic-card"
      >
        <div class="topic-title van-multi-ellipsis--l2">
          <span>{{ topic.title }}</span>
          <div class="topic-actions">
            <van-icon 
              name="arrow-down" 
              v-if="expandedTopicId !== topic.id" 
              color="#999" 
              size="14" 
              @click.stop="toggleTopicDetail(topic.id)"
              class="toggle-icon"
            />
            <van-icon 
              name="arrow-up" 
              v-if="expandedTopicId === topic.id" 
              color="#999" 
              size="14" 
              @click.stop="toggleTopicDetail(topic.id)"
              class="toggle-icon"
            />
            <!-- 主题删除按钮 - 仅自己发布的主题显示 -->
            <van-icon 
              name="delete" 
              v-if="topic.author === currentUser" 
              color="#f44" 
              size="14" 
              @click.stop="deleteTopic(topicIndex)"
              class="delete-icon"
            />
          </div>
        </div>
        
        <div class="topic-info">
          <div class="author">
            <van-icon name="user-o" size="12" /> {{ topic.author }}
          </div>
          <div class="date">{{ topic.date }}</div>
          <div class="reply-count">
            <van-icon name="comment-o" size="12" /> {{ topic.replyCount }}
          </div>
        </div>
        
        <!-- 主题详情和评论区 -->
        <div 
          class="topic-detail" 
          v-if="expandedTopicId === topic.id"
        >
          <div class="topic-content">
            {{ topic.content }}
          </div>
          
          <!-- 评论列表 -->
          <div class="comments-list">
            <h4>评论 ({{ topic.replyCount }})</h4>
            <div 
              v-for="(comment, commentIndex) in topic.comments" 
              :key="comment.id" 
              class="comment-item"
            >
              <div class="comment-header">
                <div class="comment-author">{{ comment.author }}</div>
                <div class="comment-actions">
                  <!-- 删除按钮 - 仅自己的评论显示 -->
                  <van-icon 
                    name="delete" 
                    v-if="comment.author === currentUser" 
                    color="#f44" 
                    size="12" 
                    @click.stop="deleteComment(topicIndex, commentIndex)"
                    class="action-icon"
                  />
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-date">{{ comment.date }}</div>
            </div>
            
            <!-- 评论为空时显示 -->
            <div 
              class="no-comments" 
              v-if="topic.comments.length === 0"
            >
              暂无评论，快来发表你的看法吧！
            </div>
          </div>
          
          <!-- 评论输入框 -->
          <div class="add-comment">
            <van-field
              v-model="newComment.content"
              placeholder="写下你的评论..."
              type="textarea"
              rows="2"
              autosize
              @keyup.enter="addComment(topicIndex)"
            />
            <van-button 
              round 
              type="primary" 
              color="#8b4513"
              @click="addComment(topicIndex)"
              :disabled="!newComment.content.trim()"
            >
              发表评论
            </van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { showToast } from 'vant';

export default {
  data() {
    return {
      currentUser: '我', // 当前登录用户
      topics: [
        {
          id: 1,
          title: "求推荐编程类二手书籍",
          author: "张三",
          date: "2024-01-01",
          replyCount: 2,
          content: "最近想学习Python和Java，有没有推荐的二手编程书籍？希望价格实惠，内容实用。",
          comments: [
            {
              id: 101,
              author: "李四",
              content: "《Python编程从入门到实践》这本书很不错，适合初学者。",
              date: "2024-01-02"
            },
            {
              id: 102,
              author: "我",
              content: "我有《Effective Java》第3版，9成新，价格可商量。",
              date: "2024-01-03"
            }
          ]
        },
        {
          id: 2,
          title: "出售文学名著二手书",
          author: "我",
          date: "2024-01-02",
          replyCount: 1,
          content: "本人有一批文学名著二手书出售，包括《红楼梦》《战争与和平》《百年孤独》等，价格从优，有意者请联系。",
          comments: [
            {
              id: 201,
              author: "赵六",
              content: "《百年孤独》多少钱？有笔记吗？",
              date: "2024-01-04"
            }
          ]
        }
      ],
      filteredTopics: [],
      searchKeyword: '',
      
      // 创建主题相关数据
      isCreatingTopic: false,
      newTopic: {
        title: '',
        content: '',
        author: '我'
      },
      
      // 评论相关数据
      expandedTopicId: null,
      newComment: {
        content: '',
        author: '我'
      },
      
      // 表单验证
      titleError: '',
      contentError: ''
    };
  },
  created() {
    this.filteredTopics = [...this.topics];
  },
  computed: {
    isFormValid() {
      return !this.titleError && !this.contentError && 
             this.newTopic.title.trim() && this.newTopic.content.trim();
    }
  },
  methods: {
    onSearch() {
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        this.filteredTopics = this.topics.filter(topic => {
          return topic.title.toLowerCase().includes(keyword) || 
                 topic.content.toLowerCase().includes(keyword);
        });
      } else {
        this.filteredTopics = [...this.topics];
      }
    },
    onCancelSearch() {
      this.searchKeyword = '';
      this.filteredTopics = [...this.topics];
    },
    startCreateTopic() {
      this.newTopic = { title: '', content: '', author: this.currentUser };
      this.titleError = '';
      this.contentError = '';
      this.isCreatingTopic = true;
    },
    cancelCreateTopic() {
      this.isCreatingTopic = false;
    },
    toggleTopicDetail(topicId) {
      this.expandedTopicId = this.expandedTopicId === topicId ? null : topicId;
      this.newComment.content = '';
    },
    
    // 创建主题相关方法
    validateTitle() {
      if (!this.newTopic.title.trim()) {
        this.titleError = '主题标题不能为空';
      } else if (this.newTopic.title.length > 50) {
        this.titleError = '主题标题不能超过50个字符';
      } else {
        this.titleError = '';
      }
    },
    
    validateContent() {
      if (!this.newTopic.content.trim()) {
        this.contentError = '主题内容不能为空';
      } else if (this.newTopic.content.length < 10) {
        this.contentError = '主题内容不能少于10个字符';
      } else {
        this.contentError = '';
      }
    },
    
    submitTopic() {
      this.validateTitle();
      this.validateContent();
      
      if (!this.isFormValid) return;
      
      const newId = Math.max(...this.topics.map(t => t.id), 0) + 1;
      const now = new Date();
      const formattedDate = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
      
      this.topics.unshift({
        id: newId,
        title: this.newTopic.title,
        author: this.currentUser,
        date: formattedDate,
        replyCount: 0,
        content: this.newTopic.content,
        comments: []
      });
      
      this.filteredTopics = [...this.topics];
      this.isCreatingTopic = false;
      showToast({ message: '主题发布成功！', icon: 'success' });
    },
    
    // 删除自己发布的主题
    deleteTopic(topicIndex) {
      const topic = this.topics[topicIndex];
      if (topic && topic.author === this.currentUser) {
        this.topics.splice(topicIndex, 1);
        this.filteredTopics = [...this.topics];
        
        // 如果删除的是当前展开的主题，重置展开状态
        if (this.expandedTopicId === topic.id) {
          this.expandedTopicId = null;
        }
        
        showToast({ message: '主题已删除', icon: 'success' });
      }
    },
    
    // 评论相关方法
    addComment(topicIndex) {
      if (!this.newComment.content.trim()) {
        showToast('评论内容不能为空');
        return;
      }
      
      const topic = this.topics[topicIndex];
      if (!topic) return;
      
      const newCommentId = topic.comments.length 
        ? Math.max(...topic.comments.map(c => c.id)) + 1 
        : topic.id * 100 + 1;
      
      const now = new Date();
      const formattedDate = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
      
      topic.comments.push({
        id: newCommentId,
        author: this.currentUser,
        content: this.newComment.content,
        date: formattedDate
      });
      
      topic.replyCount = topic.comments.length;
      this.newComment.content = '';
      showToast({ message: '评论发布成功！', icon: 'success' });
    },
    
    // 删除评论
    deleteComment(topicIndex, commentIndex) {
      const topic = this.topics[topicIndex];
      if (!topic) return;
      
      if (commentIndex !== -1 && commentIndex < topic.comments.length) {
        topic.comments.splice(commentIndex, 1);
        topic.replyCount = topic.comments.length;
        showToast({ message: '评论已删除', icon: 'success' });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.secondhand-forum {
  background-color: #f9f5ed;
  min-height: 100vh;
  padding-bottom: 100px;
	padding-top: 46px;
  
  .van-search {
    padding: 10px;
    background-color: #f5e8d0;
    margin-bottom: 10px;
    
    :deep(.van-search__content) {
      background-color: white;
      border-radius: 20px;
    }
  }
  
  .forum-actions {
    padding: 10px;
    background-color: white;
    margin: 0 10px 10px;
    border-radius: 8px;
  }
  
  // 创建主题区域
  .create-topic-area {
    padding: 15px;
    background-color: white;
    margin: 10px;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    .topic-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f5f5f5;
      
      h3 {
        margin: 0;
        font-size: 16px;
        color: #333;
        font-weight: 500;
      }
    }
    
    .topic-form {
      .form-error {
        color: #f44;
        font-size: 12px;
        margin: 5px 0 10px;
        padding-left: 5px;
      }
      
      .van-field {
        margin-bottom: 15px;
      }
    }
  }
  
  .topic-list {
    padding: 0 10px;
    
    .topic-card {
      background-color: white;
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 10px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      padding: 15px;
      
      .topic-title {
        font-size: 16px;
        line-height: 1.4;
        color: #333;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
      }
      
      .topic-actions {
        display: flex;
        align-items: center;
        gap: 12px;
      }
      
      .toggle-icon, .delete-icon {
        cursor: pointer;
        padding: 4px;
      }
      
      .topic-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #999;
        margin-bottom: 10px;
        padding-bottom: 8px;
        border-bottom: 1px solid #f5f5f5;
        
        .author, .reply-count {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
      
      // 主题详情和评论区
      .topic-detail {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #eee;
        
        .topic-content {
          font-size: 14px;
          line-height: 1.6;
          color: #666;
          margin-bottom: 20px;
          padding-bottom: 10px;
          border-bottom: 1px dashed #eee;
        }
        
        .comments-list {
          margin-bottom: 20px;
          
          h4 {
            font-size: 15px;
            color: #333;
            margin: 0 0 15px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
          }
          
          .comment-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f5f5f5;
            
            &:last-child {
              border-bottom: none;
            }
            
            .comment-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 5px;
            }
            
            .comment-author {
              font-size: 13px;
              font-weight: 500;
              color: #8b4513;
            }
            
            .comment-actions {
              display: flex;
              gap: 10px;
            }
            
            .action-icon {
              cursor: pointer;
              padding: 2px;
            }
            
            .comment-content {
              font-size: 14px;
              color: #666;
              margin-bottom: 5px;
              line-height: 1.5;
            }
            
            .comment-date {
              font-size: 11px;
              color: #999;
              margin-bottom: 8px;
            }
          }
          
          .no-comments {
            font-size: 13px;
            color: #999;
            text-align: center;
            padding: 20px 0;
            background-color: #f9f9f9;
            border-radius: 4px;
          }
        }
        
        .add-comment {
          .van-textarea {
            margin-bottom: 10px;
          }
          
          .van-button {
            width: 100%;
          }
        }
      }
    }
    
    .empty-topic {
      padding: 40px 20px;
      text-align: center;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      margin: 10px;
      
      p {
        margin: 10px 0;
        color: #999;
        font-size: 14px;
      }
    }
  }
}
</style>
